package com.twentyOne.ClothingLand.dao.impl;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.twentyOne.ClothingLand.dao.BaseDAO;
import com.twentyOne.ClothingLand.dao.IStockDAO;
import com.twentyOne.ClothingLand.vo.Stock;

public class StockDAO extends BaseDAO implements IStockDAO {

	@Override
	public void addStock(Stock stock) {
		
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(stock);
		tx.commit();
		session.close();
		
	}

	@Override
	public void deleteStock(Stock stock) {
		
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		String hql = "delete Stock where id = " + stock.getId();
		Query query = session.createQuery(hql);
		query.executeUpdate();
		tx.commit();
		session.close();
		
	}

	@Override
	public void modifyStock(Stock stock) {
		
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		String hql = "update Stock set quantity=:quantity where id=:id";
		Query query = session.createQuery(hql);
		query.setInteger("quantity", stock.getQuantity());
		query.setInteger("id", stock.getId());
		query.executeUpdate();
		tx.commit();
		session.close();
		
	}

	@Override
	public List<Stock> searchAllStock(int stockId, int type) {
		
		Session session = getSession();
		String hql = "from Stock where stockId = " + stockId + " and type = " + type;
		Query query = session.createQuery(hql);
		List<Stock> list = query.list();
		session.close();
		if(list.size() != 0)
			return list;
		else 
			return null;
		
	}

	@Override
	public Stock searchStockByInfo(int stockId, int type, String barcode) {

		Session session = getSession();
		String hql = "from Stock as s where s.stockId = " + stockId + " and s.type = " + type + " and s.barcode = " + barcode;
		Query query = session.createQuery(hql);
		List<Stock> list = query.list();
		session.close();
		if(list.size() != 0) {
			Stock stock = list.get(0);
			return stock;
		}else {
			return null;
		}
	
	}

}
